package com.lee.transactionaldemo.service;

import com.lee.transactionaldemo.entity.User;
import com.lee.transactionaldemo.mapper.UserMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import java.util.UUID;

/**
 * @author ：liylw
 * @date ：Created in 2021/4/22 21:29
 */
@Service
@Slf4j
public class TransactionService {

    @Autowired
    private UserMapper userMapper;

    private User createUser(){
        User user = new User();
        user.setName(UUID.randomUUID().toString());
        return user;
    }


    /**
     * 调用私有方法，事务不好使
     */
    public void saveUserCallPrivate() {
        saveUserPrivate();
    }

    @Transactional()
    private void saveUserPrivate(){
        userMapper.insert(createUser());
        throw new RuntimeException("saveUserPrivate");
    }


    /**
     * 调用this.方法 事务也是不好用的
     */
    public void saveUserCallThis() {
        this.saveUserThis();
    }

    @Transactional()
    public void saveUserThis(){
        userMapper.insert(createUser());
        throw new RuntimeException("saveUserThis");
    }



    @Autowired
    private TransactionService self;

    /**
     * 这回就好使了
     */
    public void saveUserCallSelf() {
        self.saveUserThis();
    }

    @Transactional()
    public void saveUserSelf(){
        userMapper.insert(createUser());
        throw new RuntimeException("saveUserSelf");
    }


    /**
     * try-catch 后 事务不好使
     */
    @Transactional()
    public void saveUserWithTryCatch(){
        try {
            userMapper.insert(createUser());
            throw new RuntimeException("saveUserWithTryCatch");
        } catch (RuntimeException e) {
            e.printStackTrace();
        }
    }

    /**
     * try-catch 后 事务不好使,手动回滚
     */
    @Transactional()
    public void saveUserWithTryCatchRight(){
        try {
            userMapper.insert(createUser());
            throw new RuntimeException("saveUserWithTryCatch");
        } catch (RuntimeException e) {
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();

        }
    }



    /**
     * 默认是RuntimeException和Error
     * @throws Exception
     */
    @Transactional()
    public void saveUserThrowException() throws Exception {
            userMapper.insert(createUser());
            throw new Exception("saveUserThrowException");
    }


    /**
     * 默认是RuntimeException和Error,手动rollbackFor
     * @throws Exception
     */
    @Transactional(rollbackFor = Exception.class)
    public void saveUserThrowExceptionRollbackFor() throws Exception {
        userMapper.insert(createUser());
        throw new Exception("saveUserThrowException");
    }
}
